package com.epoint.androidphone.mobileoa.ui.todostandard;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.epoint.androidmobile.bizlogic.todo.model.OperationInfoModel;
import com.epoint.androidmobile.bizlogic.todo.model.TargetActivityInfoModel;
import com.epoint.androidmobile.bizlogic.todo.model.TransactorModel;
import com.epoint.androidmobile.core.control.ControlsHelp;
import com.epoint.androidmobile.core.control.ToastUtil;
import com.epoint.androidphone.R;
import com.epoint.androidphone.mobileoa.ui.contacts.ContactsListView;
import com.epoint.androidphone.mobileoa.ui.superview.SuperPhonePage;
import com.epoint.androidmobile.bizlogic.todo.task.Handle_DealWaitHandle_Task;
import com.epoint.androidmobile.bizlogic.todo.model.ActivityInfoModel;

/**
 * @author liyc
 * @time 2013-5-13 上午9:32:44
 * @annomation 送下一步处理
 */
public class TodoStandardNextStepView extends SuperPhonePage {
	TextView tvCurrentOperation;
	OperationInfoModel oim;
	CheckBox cbMSG;
	Spinner spJjcd;
	String[] jjcdStr = new String[] { "一般", "重要", "紧急" };
	LinearLayout llNextPersons;
	ActivityInfoModel activityInfoModel;
	Button btSubmit;
	List<Integer> idsList = new ArrayList<Integer>();
	EditText etOpinion;
	long submitTaskId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addContentViewAndTitle(R.layout.todostandardnextstepview, "事项处理");
		etOpinion = (EditText) findViewById(R.id.etOpinion);
		btSubmit = (Button) findViewById(R.id.btSubmit);
		btSubmit.setOnClickListener(this);
		llNextPersons = (LinearLayout) findViewById(R.id.llNextPersons);
		tvCurrentOperation = (TextView) findViewById(R.id.tvCurrentOperation);
		cbMSG = (CheckBox) findViewById(R.id.cbMSG);
		spJjcd = (Spinner) findViewById(R.id.spJjcd);
		oim = (OperationInfoModel) getIntent().getSerializableExtra(
				"OperationInfoModel");
		activityInfoModel = (ActivityInfoModel) getIntent()
				.getSerializableExtra("activityInfoModel");

		ArrayAdapter<String> jjcdAdapter = ControlsHelp.getSPAdapter(this);
		for (String s : jjcdStr) {
			jjcdAdapter.add(s);
		}
		spJjcd.setAdapter(jjcdAdapter);

		setOperationName(activityInfoModel.ActivityDispName, oim.OperationName);
		// 转交
		if ("shift".equals(oim.OperationType)) {
			int fz30 = getIntent().getIntExtra("fz30", 0);
			TargetActivityInfoModel model = new TargetActivityInfoModel();
			model.ActivityName = "送" + oim.OperationName;
			model.ActivityGuid = "";
			model.DefaultTransactorList = new ArrayList<TransactorModel>();
			model.Is_TargetTransactor_Editable = "true";
			model.TransactorAllowMaxCount = "";
			model.TransactorFilterList = new ArrayList<TransactorModel>();
			addPersonChoose(model);
			// 退回
		} else if ("back".equals(oim.OperationType)) {
			TargetActivityInfoModel model2 = new TargetActivityInfoModel();
			model2.ActivityName = "退回";
			model2.ActivityGuid = "";
			model2.DefaultTransactorList = new ArrayList<TransactorModel>();
			model2.Is_TargetTransactor_Editable = "true";
			model2.TransactorAllowMaxCount = "";
			model2.TransactorFilterList = new ArrayList<TransactorModel>();
			addPersonChoose(model2);
			// 送下一步
		} else if ("pass".equals(oim.OperationType)
				|| "pass_transition".equals(oim.OperationType)) {
			// add by wangzhigang at 2013-07-24 08:36
			// desc:整合批办、阅读流程
			if ("1".equals(oim.IsSongPY)) {
				if ("0".equals(oim.PYNeedUsers)) {
					// 阅读

				} else {
					// 送批办、送阅读
					TargetActivityInfoModel model = new TargetActivityInfoModel();
					model.ActivityName = "送批办";
					model.ActivityGuid = "";
					model.DefaultTransactorList = new ArrayList<TransactorModel>();
					model.Is_TargetTransactor_Editable = "true";
					model.TransactorAllowMaxCount = "";
					model.TransactorFilterList = new ArrayList<TransactorModel>();
					addPersonChoose(model);
					TargetActivityInfoModel model2 = new TargetActivityInfoModel();
					model2.ActivityName = "送阅读";
					model2.ActivityGuid = "";
					model2.DefaultTransactorList = new ArrayList<TransactorModel>();
					model2.Is_TargetTransactor_Editable = "true";
					model2.TransactorAllowMaxCount = "";
					model2.TransactorFilterList = new ArrayList<TransactorModel>();
					addPersonChoose(model2);
				}
				// ----------------end add by wangzhigang at 2013-07-24 08:36
			} else if (activityInfoModel.SplitType.equals("30")) {
				int fz30 = getIntent().getIntExtra("fz30", 0);
				addPersonChoose(oim.TargetActivityList.get(fz30));
			} else if (activityInfoModel.SplitType.equals("20")) {
				int[] chooseArray = getIntent().getIntArrayExtra("fz20");
				for (int i = 0; i < chooseArray.length; i++) {
					addPersonChoose(oim.TargetActivityList.get(chooseArray[i]));
				}
			} else if (activityInfoModel.SplitType.equals("10")) {
				for (int i = 0; i < oim.TargetActivityList.size(); i++) {
					addPersonChoose(oim.TargetActivityList.get(i));
				}
			}
		}
	}

	public void addPersonChoose(final TargetActivityInfoModel tai) {
		LayoutInflater mInflater = LayoutInflater.from(getContext());
		final List<TransactorModel> chooseFilterUser = new ArrayList<TransactorModel>();
		LinearLayout lln = (LinearLayout) mInflater.inflate(
				R.layout.nextpersoncontrol, null);
		TextView tvNextTitle = (TextView) lln.findViewById(R.id.tvNextTitle);
		final EditText etChoosePerson = (EditText) lln
				.findViewById(R.id.etChoosePerson);
		etChoosePerson.setId(tai.hashCode());
		etChoosePerson.setTag(etChoosePerson.getId(), tai);
		etChoosePerson.setTag("");
		idsList.add(etChoosePerson.getId());
		ImageView ivDeletePersonChoose = (ImageView) lln
				.findViewById(R.id.ivDeletePersonChoose);

		ivDeletePersonChoose
				.setOnClickListener(new android.view.View.OnClickListener() {

					@Override
					public void onClick(View v) {
						etChoosePerson.setTag("");
						etChoosePerson.setText("");
						chooseFilterUser.clear();
					}
				});

		if (tai.DefaultTransactorList.size() > 0) {
			String defaultguids = "";
			String defaultnames = "";
			for (TransactorModel t : tai.DefaultTransactorList) {
				defaultguids += t.UserGuid + ";";
				defaultnames += t.DisplayName + ";";
			}
			etChoosePerson.setText(defaultnames);
			etChoosePerson.setTag(defaultguids);
		}

		if ("20".equals(tai.Is_TargetTransactor_Editable)) {
			ivDeletePersonChoose.setVisibility(View.GONE);
			etChoosePerson.setEnabled(false);
			lln.setVisibility(View.GONE);
		}

		etChoosePerson
				.setOnClickListener(new android.view.View.OnClickListener() {
					@Override
					public void onClick(View v) {

						if ("20".equals(tai.Is_TargetTransactor_Editable)) {
							return;
						}

						if (tai.TransactorFilterList.size() > 0) {
							final String[] names = new String[tai.TransactorFilterList
									.size()];
							final boolean[] checkedItems = new boolean[names.length];

							for (int i = 0; i < names.length; i++) {
								names[i] = tai.TransactorFilterList.get(i).DisplayName;
								if (chooseFilterUser
										.contains(tai.TransactorFilterList
												.get(i))) {
									checkedItems[i] = true;
								}
							}

							Builder builder = new AlertDialog.Builder(
									getContext());
							builder.setTitle("选择处理人");
							builder.setMultiChoiceItems(names, checkedItems,
									new OnMultiChoiceClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which, boolean isChecked) {
											if (isChecked) {
												if (!chooseFilterUser
														.contains(tai.TransactorFilterList
																.get(which))) {
													chooseFilterUser
															.add(tai.TransactorFilterList
																	.get(which));
												}
											} else {
												if (chooseFilterUser
														.contains(tai.TransactorFilterList
																.get(which))) {
													chooseFilterUser
															.remove(tai.TransactorFilterList
																	.get(which));
												}
											}
										}
									});
							builder.setPositiveButton("确定",
									new OnClickListener() {
										@Override
										public void onClick(
												DialogInterface arg0, int arg1) {
											String names = "";
											String guids = "";
											for (int i = 0; i < chooseFilterUser
													.size(); i++) {
												names += chooseFilterUser
														.get(i).DisplayName
														+ ";";
												guids += chooseFilterUser
														.get(i).UserGuid + ";";
											}
											etChoosePerson.setText(names);
											etChoosePerson.setTag(guids);
										}

									});
							builder.setNegativeButton("取消", null);
							AlertDialog dialog = builder.create();
							dialog.show();
							return;
						}

						Intent intent = new Intent(getContext(),
								ContactsListView.class);
						intent.putExtra("enterflag", 2);
						intent.putExtra("EnterClassName", getContext()
								.getClass().getName());
						startActivityForResult(intent, etChoosePerson.getId());
						System.out.println("ID:" + etChoosePerson.getId());
					}
				});
		tvNextTitle.setText(Html.fromHtml("<font color=red>【"
				+ tai.ActivityName + "】</font>处理人："));
		llNextPersons.addView(lln);

	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		if (v == btSubmit) {
			StringBuilder sb = new StringBuilder();
			// add by wangzhigang at 2013-07-24 08:36
			// desc:整合批办、阅读流程
			HashMap<String, Object> params = getPassMap();
			params.put("PiBanUserGuidLst", "");
			params.put("YueDuUserGuidLst", "");

			if ("1".equals(oim.IsSongPY) && "1".equals(oim.PYNeedUsers)) {

				EditText et = (EditText) llNextPersons.findViewById(idsList
						.get(0));
				params.put("PiBanUserGuidLst", et.getTag().toString());
				EditText et2 = (EditText) llNextPersons.findViewById(idsList
						.get(1));
				params.put("YueDuUserGuidLst", et2.getTag().toString());

			} else if ("1".equals(oim.IsSongPY) && "0".equals(oim.PYNeedUsers)) {
				// 无处理

			} else {
				// ----------------end add by wangzhigang at 2013-07-24 08:36
				sb.append("<TargetActivityList>");
				for (int i = 0; i < idsList.size(); i++) {
					EditText et = (EditText) llNextPersons.findViewById(idsList
							.get(i));
					TargetActivityInfoModel t = (TargetActivityInfoModel) et
							.getTag(idsList.get(i));
					sb.append("<TargetActivityInfo>");
					sb.append("<ActivityGuid>");
					sb.append(t.ActivityGuid);
					sb.append("</ActivityGuid>");
					sb.append("<HandlePersonList>");
					String[] guids = et.getTag().toString().split(";");

					boolean isClickable = et.isEnabled();
					if (isClickable && et.getTag().toString().length() == 0) {
						ControlsHelp.Check_EditText_Blank_Warning(et, "请选择处理人");
						return;
					}

					for (int j = 0; j < guids.length; j++) {
						sb.append("<HandlePerson>");
						sb.append(guids[j]);
						sb.append("</HandlePerson>");
					}
					sb.append("</HandlePersonList>");
					sb.append("</TargetActivityInfo>");
				}
				sb.append("</TargetActivityList>");

				if (oim.Is_RequireOpinion.equals("10")
						&& etOpinion.getText().toString().length() == 0) {
					ToastUtil.toastWorning(this, "必须添加意见！");
					return;
				}

			}
			params.put("MessageItemGuid",
					getIntent().getStringExtra("MessageItemGuid"));
			params.put("TargetActivityList", sb.toString());
			params.put("Opinion", etOpinion.getText().toString());
			params.put("OperationGuid", oim.OperationGuid);
			params.put("PDFPath", TodoStandardDetailView.savePath);
			int sendmsg;
			if (cbMSG.isChecked()) {
				sendmsg = 1;
			} else {
				sendmsg = 0;
			}
			params.put("SendSms", sendmsg + "");

			int jjcdint = 0;
			if (spJjcd.getSelectedItemPosition() == 0) {
				jjcdint = 1;
			} else if (spJjcd.getSelectedItemPosition() == 1) {
				jjcdint = 2;
			} else if (spJjcd.getSelectedItemPosition() == 2) {
				jjcdint = 3;
			}
			params.put("SendSms_JJCD", jjcdint + "");
			showDialogMiddle("正在提交...");
			submitTaskId = new Handle_DealWaitHandle_Task(this, params)
					.startTask();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			System.out.println("requestCode:" + requestCode);
			((EditText) llNextPersons.findViewById(requestCode)).setText(data
					.getStringExtra("names"));
			((EditText) llNextPersons.findViewById(requestCode)).setTag(data
					.getStringExtra("guids"));
		}
	}

	private void setOperationName(String stepName, String operateName) {
		tvCurrentOperation.setText(Html.fromHtml("当前步骤：<font color=red>"
				+ stepName + "</font>；当前操作：<font color=red>" + operateName
				+ "</font>"));
	}

	@Override
	public void refreshUI(long taskId, Object obj) {
		super.refreshUI(taskId, obj);
		if (taskId == submitTaskId) {
			if (validateXML(obj)) {
				ToastUtil.toastLong(this, "处理成功");
				setResult(RESULT_OK);
				finish();
			}
		}
	}
}
